package nccloud.web.erm.action.expenseaccount.jkbx;

import com.alibaba.fastjson.JSONObject;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.Map.Entry;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArraySet;
import nc.nccloud.dto.erm.expenseaccount.BXBillVO;
import nc.nccloud.util.erm.expenseaccount.RequestParam;
import nc.pubitf.erm.mergerecord.IErmMergeRecordService;
import nc.vo.ep.bx.BXBusItemVO;
import nc.vo.ep.bx.BXHeaderVO;
import nc.vo.ep.bx.BxcontrastVO;
import nc.vo.er.exception.BugetAlarmBusinessException;
import nc.vo.er.exception.BugetControlBusinessException;
import nc.vo.er.exception.ProjBudgetAlarmBusinessException;
import nc.vo.erm.accruedexpense.AccruedVerifyVO;
import nc.vo.erm.costshare.CShareDetailVO;
import nc.vo.erm.erminvoice.ErmInvoice;
import nc.vo.erm.invoicemergerecord.AggInvoiceMergeRecord;
import nc.vo.erm.invoicemergerecord.InvoiceMergeRecordDetail;
import nc.vo.jcom.lang.StringUtil;
import nc.vo.pub.CircularlyAccessibleValueObject;
import nc.vo.pub.ISuperVO;
import nc.vo.pub.SuperVO;
import nc.vo.pub.lang.UFDouble;
import nccloud.base.exception.ExceptionUtils;
import nccloud.framework.core.json.IJson;
import nccloud.framework.core.util.GridCompareUtils;
import nccloud.framework.service.ServiceLocator;
import nccloud.framework.web.container.IRequest;
import nccloud.framework.web.convert.translate.Translator;
import nccloud.framework.web.json.JsonFactory;
import nccloud.framework.web.processor.template.ExtBillCardConvertProcessor;
import nccloud.framework.web.ui.pattern.extbillcard.ExtBillCard;
import nccloud.framework.web.ui.pattern.extbillcard.ExtBillCardOperator;
import nccloud.pubitf.erm.expenseaccount.erminvoice.IErmInvoiceManageService;
import nccloud.pubitf.erm.expenseaccount.jkbx.IExpenseaccountService;
import nccloud.web.erm.action.lic.AbstractLicAction;
import nccloud.web.erm.util.expenseaccount.DataChangeLogic;

public class ExpenseaccountSaveAction extends AbstractLicAction {
	public Object doRealAction(IRequest request) {
		IJson json = JsonFactory.create();
		String read = request.read();
		ExtBillCard extbillcard = (ExtBillCard) json.fromJson(read, ExtBillCard.class);
		Map<String, Object> map = (Map) json.fromJson(extbillcard.getHead().getUserjson(), Map.class);
		RequestParam param = RequestParam.convertViewToParam(map);
		param.setParameter("templateid", extbillcard.getTempletid());
		ExtBillCardOperator oper = new ExtBillCardOperator(param.getParameter("pagecode").toString());
		ExtBillCard newExtbillcard = new ExtBillCard();
		Translator translator = new Translator();
		ExtBillCardConvertProcessor processor = new ExtBillCardConvertProcessor();
		extbillcard.setPageid(String.valueOf(param.getParameter("pagecode")));
		BXBillVO vo = (BXBillVO) processor.fromExtBillCard(extbillcard);
		this.clearAddRowNotUserField(vo);
		IExpenseaccountService service = (IExpenseaccountService) ServiceLocator.find(IExpenseaccountService.class);
		BXBillVO retvo = null;
		JSONObject retjson = null;

		
		BXHeaderVO bvo=(BXHeaderVO) vo.getParentVO();
				
		String 	hj=bvo.getZyx22();
		try {
			BXBusItemVO[] bbvos=(BXBusItemVO[]) vo.getAllChildrenVO();
			for (int i = 0; i < bbvos.length; i++) {
				if(i==0) {
				if(null!=hj) {
				bbvos[i].setDefitem46(hj);
				}
				}else {
				bbvos[i].setDefitem46(null);
				}
			}
			vo.setChildrenVO(bbvos);
			
			retvo = service.saveJKBX(vo, param);
			JSONObject jsonObj = new JSONObject();
			jsonObj.put("reimmsg", (String) param.getParameter("reimmsg"));
			if (retvo != null) {
				BXBillVO billvo = new BXBillVO();
				billvo.setParentVO(retvo.getParentVO());
				ConcurrentHashMap<String, CopyOnWriteArraySet<SuperVO>> bus = new ConcurrentHashMap();
				Set<String> pk_erminvoiceSet = new HashSet();
				Set<String> pk_erminvoiceMergeRecPkSet = new HashSet();
				List<String> pkList = new ArrayList();
				BXBusItemVO[] var21 = retvo.toJKBXBXVO().getChildrenVO();
				int var22 = var21.length;

				CopyOnWriteArraySet setbus;
				String pk;
				CopyOnWriteArraySet buvo;
				String bxPkerm;
				for (int var23 = 0; var23 < var22; ++var23) {
					BXBusItemVO child = var21[var23];
					setbus = new CopyOnWriteArraySet();
					pk = child.getTablecode();
					child.setStatus(1);
					setbus.add(child);
					if (!bus.containsKey(pk)) {
						bus.put(pk, setbus);
					} else {
						buvo = (CopyOnWriteArraySet) bus.get(pk);
						buvo.add(child);
					}

					bxPkerm = child.getPk_erminvoice();
					if (!StringUtil.isEmptyWithTrim(bxPkerm)) {
						String generatetype = child.getGeneratetype();
						if ("1".equals(generatetype)) {
							pk_erminvoiceMergeRecPkSet.add(bxPkerm);
						} else {
							pk_erminvoiceSet.add(bxPkerm);
						}
					}

					if (child.getPk_erminvoice() != null && !child.getPk_erminvoice().equals("~")
							&& !pkList.contains(child.getPk_erminvoice())) {
						pkList.add(child.getPk_erminvoice());
					}
				}

				IErmInvoiceManageService invoiceMsnsgerService = (IErmInvoiceManageService) ServiceLocator
						.find(IErmInvoiceManageService.class);
				Map<String, List<String>> bxToInvoice = new HashMap();
				Map<String, List<String>> invoiceToBx = new HashMap();
				List<ErmInvoice> allInvoiceList = new ArrayList();

				List invPkList;
				for (int i = 0; i < pkList.size(); ++i) {
					pk = (String) pkList.get(i);
					List<ErmInvoice> invoice = invoiceMsnsgerService.queryInvoiceByPk(pk);
					if (invoice != null && invoice.size() > 0) {
						allInvoiceList.add(invoice.get(0));
						List<String> ermPkList = new ArrayList();
						ermPkList.add(((ErmInvoice) invoice.get(0)).getPk_erminvoice());
						bxToInvoice.put(pk, ermPkList);
					} else {
						invPkList = invoiceMsnsgerService.queryInvoicePk(pk);
						List<String> ermPkList = new ArrayList();
						Iterator var30 = invPkList.iterator();

						while (var30.hasNext()) {
							InvoiceMergeRecordDetail detail = (InvoiceMergeRecordDetail) var30.next();
							List<ErmInvoice> inv = invoiceMsnsgerService.queryInvoiceByPk(detail.getPk_erminvoice());
							if (inv != null && inv.size() > 0
									&& !ermPkList.contains(((ErmInvoice) inv.get(0)).getPk_erminvoice())) {
								allInvoiceList.add(inv.get(0));
								ermPkList.add(((ErmInvoice) inv.get(0)).getPk_erminvoice());
							}
						}

						bxToInvoice.put(pk, ermPkList);
					}
				}

				Iterator var44 = allInvoiceList.iterator();

				while (var44.hasNext()) {
					ErmInvoice invoice = (ErmInvoice) var44.next();
					if (invoice.getSl() != null) {
						DecimalFormat df = new DecimalFormat("0.##");
						invoice.setSl(df.format((new UFDouble(invoice.getSl())).multiply(100.0D)).toString());
					}
				}

				var44 = bxToInvoice.entrySet().iterator();

				Entry entry;
				while (var44.hasNext()) {
					entry = (Entry) var44.next();
					bxPkerm = (String) entry.getKey();
					invPkList = (List) entry.getValue();
					Iterator var60 = invPkList.iterator();

					while (var60.hasNext()) {
						String pks = (String) var60.next();
						List<String> bxPkList = new ArrayList();
						bxPkList.add(bxPkerm);
						invoiceToBx.put(pks, bxPkList);
					}
				}

				jsonObj.put("bxToInvoice", bxToInvoice);
				jsonObj.put("invoiceToBx", invoiceToBx);
				int var61;
				if (pk_erminvoiceMergeRecPkSet.size() > 0) {
					IErmMergeRecordService ermMergeRecordService = (IErmMergeRecordService) ServiceLocator
							.find(IErmMergeRecordService.class);
					AggInvoiceMergeRecord[] queryMergeRecordByPks = ermMergeRecordService
							.queryMergeRecordByPks((String[]) pk_erminvoiceMergeRecPkSet.toArray(new String[0]));
					if (queryMergeRecordByPks != null && queryMergeRecordByPks.length > 0) {
						AggInvoiceMergeRecord[] var57 = queryMergeRecordByPks;
						var61 = queryMergeRecordByPks.length;

						for (int var62 = 0; var62 < var61; ++var62) {
							AggInvoiceMergeRecord aggvo = var57[var62];
							InvoiceMergeRecordDetail[] detailvos = (InvoiceMergeRecordDetail[]) ((InvoiceMergeRecordDetail[]) aggvo
									.getChildrenVO());
							InvoiceMergeRecordDetail[] var72 = detailvos;
							int var33 = detailvos.length;

							for (int var34 = 0; var34 < var33; ++var34) {
								InvoiceMergeRecordDetail detail = var72[var34];
								pk_erminvoiceSet.add(detail.getPk_erminvoice());
							}
						}
					}
				}

				if (pk_erminvoiceSet.size() > 0) {
					jsonObj.put("pk_erminvoices", pk_erminvoiceSet.toArray(new String[0]));
				}

				int var59;
				if (null != retvo.toJKBXBXVO().getContrastVO() && retvo.toJKBXBXVO().getContrastVO().length > 0) {
					setbus = new CopyOnWriteArraySet();
					BxcontrastVO[] var51 = retvo.toJKBXBXVO().getContrastVO();
					var59 = var51.length;

					for (var61 = 0; var61 < var59; ++var61) {
						BxcontrastVO bxvo = var51[var61];
						setbus.add(bxvo);
						bxvo.setStatus(1);
					}

					bus.put("er_bxcontrast", setbus);
				}

				if (null != retvo.toJKBXBXVO().getcShareDetailVo()
						&& retvo.toJKBXBXVO().getcShareDetailVo().length > 0) {
					setbus = new CopyOnWriteArraySet();
					CShareDetailVO[] var53 = retvo.toJKBXBXVO().getcShareDetailVo();
					var59 = var53.length;

					for (var61 = 0; var61 < var59; ++var61) {
						CShareDetailVO bxvo = var53[var61];
						setbus.add(bxvo);
						bxvo.setStatus(1);
					}

					bus.put("er_cshare_detail", setbus);
				}

				if (null != retvo.toJKBXBXVO().getAccruedVerifyVO()
						&& retvo.toJKBXBXVO().getAccruedVerifyVO().length > 0) {
					setbus = new CopyOnWriteArraySet();
					AccruedVerifyVO[] var55 = retvo.toJKBXBXVO().getAccruedVerifyVO();
					var59 = var55.length;

					for (var61 = 0; var61 < var59; ++var61) {
						AccruedVerifyVO bxvo = var55[var61];
						setbus.add(bxvo);
						bxvo.setStatus(1);
					}

					bus.put("accrued_verify", setbus);
				}

				if (null != allInvoiceList && allInvoiceList.size() > 0) {
					setbus = new CopyOnWriteArraySet();
					Iterator var58 = allInvoiceList.iterator();

					while (var58.hasNext()) {
						ErmInvoice invoice = (ErmInvoice) var58.next();
						setbus.add(invoice);
					}

					bus.put("invoice_Detail", setbus);
				}

				for (var44 = bus.entrySet().iterator(); var44.hasNext(); billvo
						.setChildrenVO((CircularlyAccessibleValueObject[]) null)) {
					entry = (Entry) var44.next();
					buvo = (CopyOnWriteArraySet) entry.getValue();
					if (buvo.toArray()[0].getClass().getName().equals("nc.vo.erm.accruedexpense.AccruedVerifyVO")) {
						billvo.setChildren(AccruedVerifyVO.class, (ISuperVO[]) buvo.toArray(new AccruedVerifyVO[0]));
					} else if (buvo.toArray()[0].getClass().getName().equals("nc.vo.erm.costshare.CShareDetailVO")) {
						billvo.setChildren(CShareDetailVO.class, (ISuperVO[]) buvo.toArray(new CShareDetailVO[0]));
					} else if (buvo.toArray()[0].getClass().getName().equals("nc.vo.ep.bx.BxcontrastVO")) {
						billvo.setChildren(BxcontrastVO.class, (ISuperVO[]) buvo.toArray(new BxcontrastVO[0]));
					} else if (buvo.toArray()[0].getClass().getName().equals("nc.vo.erm.erminvoice.ErmInvoice")) {
						billvo.setChildren(ErmInvoice.class, (ISuperVO[]) buvo.toArray(new ErmInvoice[0]));
					} else {
						billvo.setChildren(BXBusItemVO.class, (ISuperVO[]) buvo.toArray(new BXBusItemVO[0]));
					}

					ExtBillCard temp = oper.toCard(billvo);
					newExtbillcard.setHead(temp.getHead());
					if (null != temp.getBody(((String) entry.getKey()).toString())) {
						newExtbillcard.addBody(temp.getBody(((String) entry.getKey()).toString()));
					}
				}
			}

			newExtbillcard.setUserjson(jsonObj.toString());
			newExtbillcard.setPageid(param.getParameter("pagecode").toString());
			if (newExtbillcard != null) {
				DataChangeLogic.setViewScala(newExtbillcard.getHead(), newExtbillcard.getAllBodys());
			}

			translator.translate(newExtbillcard);
			return GridCompareUtils.compareExtBillCardGrid(extbillcard, newExtbillcard);
		} catch (Exception var36) {
			retjson = new JSONObject();
			Throwable targetEx = ExceptionUtils.unmarsh(var36);
			if (targetEx instanceof BugetAlarmBusinessException) {
				String proBudgetCheck = (String) param.getParameter("proBudgetCheck");
				if ("true".equals(proBudgetCheck)) {
					retjson.put("proBudgetCheck", "Y");
				}

				retjson.put("Alarm", "Y");
				retjson.put("success", "true");
				retjson.put("message", targetEx.getMessage());
			} else if (targetEx instanceof ProjBudgetAlarmBusinessException) {
				retjson.put("AlarmType", "Project");
				retjson.put("Alarm", "Y");
				retjson.put("success", "true");
				retjson.put("message", targetEx.getMessage());
			} else if (targetEx instanceof BugetControlBusinessException) {
				retjson.put("control", "Y");
				retjson.put("success", "false");
				retjson.put("message", targetEx.getMessage());
			} else {
				retjson.put("success", "false");
				retjson.put("message", targetEx.getMessage());
				retjson.put("stacktrace", ExceptionUtils.getStackTrace(targetEx));
			}

			return retjson;
		}
	}

	private void clearAddRowNotUserField(BXBillVO vo) {
		BXBusItemVO[] var2 = vo.toJKBXBXVO().getChildrenVO();
		int var3 = var2.length;

		int var4;
		for (var4 = 0; var4 < var3; ++var4) {
			BXBusItemVO child = var2[var4];
			if (child.getStatus() == 2) {
				child.setPk_busitem((String) null);
			}
		}

		if (null != vo.toJKBXBXVO().getContrastVO() && vo.toJKBXBXVO().getContrastVO().length > 0) {
			BxcontrastVO[] var6 = vo.toJKBXBXVO().getContrastVO();
			var3 = var6.length;

			for (var4 = 0; var4 < var3; ++var4) {
				BxcontrastVO cvo = var6[var4];
				if (cvo.getStatus() == 2) {
					cvo.setPk_bxcontrast((String) null);
				}
			}
		}

		if (null != vo.toJKBXBXVO().getcShareDetailVo() && vo.toJKBXBXVO().getcShareDetailVo().length > 0) {
			CShareDetailVO[] var7 = vo.toJKBXBXVO().getcShareDetailVo();
			var3 = var7.length;

			for (var4 = 0; var4 < var3; ++var4) {
				CShareDetailVO cvo = var7[var4];
				if (cvo.getStatus() == 2) {
					cvo.setPk_cshare_detail((String) null);
				}
			}
		}

		if (null != vo.toJKBXBXVO().getAccruedVerifyVO() && vo.toJKBXBXVO().getAccruedVerifyVO().length > 0) {
			AccruedVerifyVO[] var8 = vo.toJKBXBXVO().getAccruedVerifyVO();
			var3 = var8.length;

			for (var4 = 0; var4 < var3; ++var4) {
				AccruedVerifyVO avo = var8[var4];
				if (avo.getStatus() == 2) {
					avo.setPk_accrued_detail((String) null);
				}
			}
		}

	}
}